//
//  ShakeShakeViewController.m
//  MagicBox
//
//  Created by dllo on 16/8/16.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "PedometerViewController.h"
#import "AppDelegate.h"
#import <CoreMotion/CoreMotion.h>


@interface PedometerViewController ()
{
    
     UILabel *stepCountLabel;
    UISwitch *switchBtn;
    UISwitch *switchBtnTwo;
}
@property (nonatomic ,strong) CMPedometer *pedometer;

@property (nonatomic, strong) UIButton *myButton;

@end

@implementation PedometerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = _Pedometer;
    // Do any additional setup after loading the view.
    stepCountLabel = [[UILabel alloc] initWithFrame:CGRectMake(SCREENWIDTH / 5, 0, SCREENWIDTH - (SCREENWIDTH / 10), SCREENWIDTH - (SCREENWIDTH / 10))];
    stepCountLabel.font = [UIFont systemFontOfSize:25];
    stepCountLabel.text =@"当前步行了 0 步";
    [self.view addSubview:stepCountLabel];
    
    UIImageView *myImageView = [[UIImageView alloc] initWithFrame:CGRectMake(SCREENWIDTH / 2 - (SCREENWIDTH / 3), SCREENWIDTH * 0.5, SCREENWIDTH / 1.5, SCREENWIDTH / 1.5)];
    myImageView.layer.masksToBounds = YES;
    myImageView.layer.cornerRadius = (SCREENWIDTH / 2)/2.0f;
    myImageView.image = [UIImage imageNamed:@"Pedometer.png"];
    [self.view addSubview:myImageView];
    myImageView.userInteractionEnabled = YES;
    
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(SCREENHEIGHT / 20, SCREENWIDTH + (SCREENWIDTH / 4), SCREENHEIGHT - (SCREENHEIGHT / 20), 30)];
    titleLabel.text = @"开启记步功能(支持后台计步)";
    titleLabel.font = [UIFont systemFontOfSize:21];
    [self.view addSubview:titleLabel];
    
    
//    self.myButton = [UIButton buttonWithType:UIButtonTypeCustom];
//    _myButton.backgroundColor = [UIColor magentaColor];
//    _myButton.frame = CGRectMake(0, 0, 200, 150);
//    [myImageView addSubview:self.myButton];
//    [_myButton addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpOutside];
    
    
    
     switchBtn = [[UISwitch alloc] init];
    switchBtn.frame = CGRectMake(SCREENHEIGHT / 2 - (SCREENWIDTH / 8), SCREENWIDTH + (SCREENWIDTH / 17), 80, 30);
    [switchBtn addTarget:self action:@selector(openOrCloseCollectStep:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:switchBtn];
    
    [self  gotoOpenStepCountFunction];
    
    
    
}

-(void)viewWillAppear:(BOOL)animated{
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(numberOfStepsChanged:) name:@"numberOfSteps" object:nil];
    
}


-(void)viewWillDisappear:(BOOL)animated{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"numberOfSteps" object:nil];
    
}



-(void)numberOfStepsChanged:(NSNotification *)notif{
    
    
    NSString * numberOfSteps = [[notif userInfo] objectForKey:@"numberOfSteps"];
    
    NSLog(@"***********   ********** numberOfSteps  %@   *************",numberOfSteps);
    dispatch_async(dispatch_get_main_queue(), ^{
        
        stepCountLabel.text =[NSString stringWithFormat:@"当前步行了%@步",numberOfSteps];
        
    });
    
    
    
}


-(void)openOrCloseCollectStep:(UISwitch *)switchBtn1{
    
    
    if (switchBtn1.on) {
        
        [self  gotoOpenStepCountFunction];
        
        return;
        
    }else{
        
        [self gotoCloseStepCountFucntion];
        
    }
}






-(void)gotoOpenStepCountFunction{
    
    _pedometer = [[AppDelegate share ] sharedPedometer];
    
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"startStepCount"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    if ([CMPedometer isStepCountingAvailable]) {
        [_pedometer startPedometerUpdatesFromDate:[NSDate date] withHandler:^(CMPedometerData * _Nullable pedometerData, NSError * _Nullable error) {
            
            if (error) {
                NSLog(@"error====%@",error);
                
                [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"startStepCount"];
                [[NSUserDefaults standardUserDefaults] synchronize];
                
            }else {
                NSLog(@"BBB步数====%@",pedometerData.numberOfSteps);
                NSLog(@"BBB距离====%@",pedometerData.distance);
                
                NSDictionary *dic =[NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"%@",pedometerData.numberOfSteps],@"numberOfSteps", nil];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"numberOfSteps" object:nil userInfo:dic];
                
                
            }
            
        }];
        
    }else{
        
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"该设备不支持,(iPhone5以上设备支持)?" message:@"" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cation1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            switchBtn.frame = CGRectMake(- (SCREENHEIGHT * 10), SCREENWIDTH + (SCREENWIDTH / 17), 80, 30);
            
            
            
            return ;
        }];
        
        UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
            
            
            
        }];
        
        [alert addAction:cation1];
        [alert addAction:action2];
        
        [self presentViewController:alert animated:YES completion:^{
            
            
        }];
        
        
        
        
        NSLog(@"计步器不可用");
        
        [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"startStepCount"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
    
    
}

-(void)gotoCloseStepCountFucntion{
    
    if ([CMPedometer isStepCountingAvailable]) {
        
        _pedometer = [[AppDelegate share] sharedPedometer];
        [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"startStepCount"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        [_pedometer stopPedometerUpdates];
        
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
